#include <iostream>
#include <fstream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

using namespace std;

int gSliderPosition = 0;    //滑动条位置
int gRun = 1, gDontset = 0; //单步模式
cv::VideoCapture gCap;      //

//点击滑动条后调用该回调函数,设置是视频显示到滑动条帧位置,并设置gRun=1
void onTrackbarSlide(int pos, void *)
{
    gCap.set(cv::CAP_PROP_POS_FRAMES, pos);
    if (!gDontset)
        gRun = 1;
    gDontset = 0;
}

int main(int argc, char** argv)
{
    cv::namedWindow("Example2_4", cv::WINDOW_AUTOSIZE);
    gCap.open("../../resource/video/test_for_car.mp4");
    int frames = (int)gCap.get(cv::CAP_PROP_FRAME_COUNT);
    int tmpw = (int)gCap.get(cv::CAP_PROP_FRAME_WIDTH);
    int tmph = (int)gCap.get(cv::CAP_PROP_FRAME_HEIGHT);
    cout << "Video has " << frames << " frames of dimensions("
         << tmpw << ", " << tmph << ")." << endl; //输出帧信息

    cv::createTrackbar("Position", "Example2_4",
                       &gSliderPosition,frames, onTrackbarSlide);

    cv::Mat frame;
    for(;;)
    {
        if (gRun != 0)  //任何模式下
        {
            gCap >> frame;
            if (frame.empty())
                break;
            int currentPos = (int)gCap.get(cv::CAP_PROP_POS_FRAMES);
            gDontset = 1;

            //滑动条同步当前帧
            cv::setTrackbarPos("Position", "Example2_4", currentPos);
            cv::imshow("Example2_4", frame);
            gRun -= 1;      //gun最大为1,只执行一次显示frame
        }
        char c = (char)cv::waitKey(10);
        if (c == 's')       //单步模式 gRun=1
        {
            gRun = 1;
            cout << "Single step, run = " << gRun << endl;
        }
        if (c == 'r')       //连续模式 gRun=-1
        {
            gRun = -1;
            cout << "Run mode, run = " << gRun << endl;
        }
        if (c == 27)
            break;
    }

    return 0;
}
